package com.GLM.Viewer.FirstLogin;

import java.io.IOException;
import java.util.ArrayList;
import java.util.concurrent.atomic.AtomicBoolean;

import org.apache.http.client.ClientProtocolException;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.text.InputType;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.animation.AccelerateInterpolator;
import android.view.animation.Animation;
import android.view.animation.Animation.AnimationListener;
import android.view.animation.AnimationUtils;
import android.view.animation.DecelerateInterpolator;
import android.view.animation.Interpolator;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.GLM.Constants.Constant;
import com.GLM.Entity.LoginAccountEntity;
import com.GLM.Entity.ShowMeetEntity;
import com.GLM.Entity.ShowMsgEntity;
import com.GLM.Entity.ShowRingEntity;
import com.GLM.Entity.UserInfoEntity;
import com.GLM.Tools.DB.DAO.UserInfoDAO;
import com.GLM.Tools.Utils.Rotate3DAnimation;
import com.GLM.Tools.Utils.ViewsUtil;
import com.GLM.Tools.Utils.Image.AsynImageLoader;
import com.GLM.Tools.Utils.Image.AvatarUtil;
import com.GLM.Tools.Utils.JSON.JSONResponse;
import com.GLM.Tools.Utils.JSON.JSONResponse.Status;
import com.GLM.Tools.Utils.JSON.JSONUtil;
import com.GLM.Viewer.R;
import com.GLM.Viewer.Main.MainActivity;
import com.GLM.Viewer.Party.PartyMeetingPlaceActivity;
import com.google.gson.Gson;

public class FirstLoginActivity extends Activity {
	private final static int LOGINING_CODE = 1;
	private final static int LOGINED_CODE = 2;
	
	private ViewGroup mContainer;
	private ViewGroup mAnimContainer1;
	private ImageView mAnimImageViewMsg1;
	private TextView mAnimTextViewMsg1;
	private TextView mAnimNameView1;

	private ViewGroup mAnimContainer2;
	private ImageView mAnimImageViewMsg2;
	private TextView mAnimTextViewMsg2;
	private TextView mAnimNameView2;

	private ViewGroup mAnimContainer3;
	private ImageView mAnimImageViewMsg3;
	private TextView mAnimTextViewMsg3;
	private TextView mAnimNameView3;

	private Drawable mAvatarTestPic;
	private int mCurrentShowLoop = 0;
	private int mShowLoopCount = 0;

	private int temp = 0;
	private AtomicBoolean mAnimCancelled;
	private DisplayNextView mDisplayNextView;
	
	private final static int MSG_STARTANIM = 123;
	private AsynImageLoader imageLoader = new AsynImageLoader();
	private ArrayList<ShowMsgEntity> mShowMsgList = new ArrayList<ShowMsgEntity>();
	private ArrayList<ShowMeetEntity> mShowMeetList = new ArrayList<ShowMeetEntity>();
	private ArrayList<ShowRingEntity> mShowRingList = new ArrayList<ShowRingEntity>();

	private Animation mLoginAnimIn;
	private Animation mLoginAnimOut;
	private View mLoginView;
	EditText usernameEdit;
	EditText passwordEdit;
	
	View mInputFieldOneLine;
	TextView mInputFieldOneLineTextView;
	EditText mInputFieldOneLineEditText;
	Animation mAnimIn;
	Animation mAnimOut;
	InputMethodManager imm;
	private ProgressDialog pd;
	int status = -1;
	private Handler mHandler = new Handler() {
		public void handleMessage(Message msg) {
			Thread thread;
			switch (msg.what) {
			case MSG_STARTANIM:
				mContainer.post(new SwapAnimationData());
				break;
			case LOGINING_CODE:
				pd =  ProgressDialog.show(FirstLoginActivity.this, "", getString(R.string.logining), true, true);
				
				thread = new Thread(new Runnable() {
				
					public void run() {
						// TODO Auto-generated method stub
						Looper.prepare();
						status = login();
						mHandler.sendEmptyMessage(LOGINED_CODE);
						Looper.loop();
					}
				});
				thread.start();
				
				break;
			case LOGINED_CODE:
				if(pd != null&& pd.isShowing()){
					pd.cancel();
				}
				if(status == Constant.RESP_STATUS_SUCCESS){
					Intent intent = new Intent(FirstLoginActivity.this, MainActivity.class);
					startActivity(intent);
					finish();
				}
				break;
			default:
				break;
			}
		}
	};
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.view_firstlogin);
		imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);

		mLoginView = (View)findViewById(R.id.main_login_layout);
		mContainer = (ViewGroup) findViewById(R.id.container);
		
		mAnimContainer1 = (ViewGroup) findViewById(R.id.anim_container1);
		mAnimImageViewMsg1 = (ImageView) findViewById(R.id.anim_image_mainmsg1);
		mAnimTextViewMsg1 = (TextView) findViewById(R.id.anim_text1);
		mAnimNameView1 = (TextView)findViewById(R.id.anim_msg_username1);

		mAnimContainer2 = (ViewGroup) findViewById(R.id.anim_container2);
		mAnimImageViewMsg2 = (ImageView) findViewById(R.id.anim_image_mainmsg2);
		mAnimTextViewMsg2 = (TextView) findViewById(R.id.anim_text2);
		mAnimNameView2 = (TextView)findViewById(R.id.anim_msg_username2);

		mAnimContainer3 = (ViewGroup) findViewById(R.id.anim_container3);
		mAnimImageViewMsg3 = (ImageView) findViewById(R.id.anim_image_mainmsg3);
		mAnimTextViewMsg3 = (TextView) findViewById(R.id.anim_text3);
		mAnimNameView3 = (TextView)findViewById(R.id.anim_msg_username3);

		mContainer.setPersistentDrawingCache(ViewGroup.PERSISTENT_ANIMATION_CACHE);
		mDisplayNextView = new DisplayNextView(Constant.ANIM_CONTAINER1_VISIABLE);

		mAnimCancelled = new AtomicBoolean(false);
		
		initInputFields();
		initAnimation();
		initRegisterInputFieldButton();
		
		Message msg = new Message();
		msg.what = MSG_STARTANIM;
		mHandler.sendMessage(msg);
	}

	private void initInputFields() {
		mInputFieldOneLine = findViewById(R.id.inputfield_oneline);
		mInputFieldOneLine.setVisibility(View.GONE);
		mInputFieldOneLineTextView = (TextView) findViewById(R.id.inputfield_title);
		mInputFieldOneLineEditText = (EditText) findViewById(R.id.inputfield_edittext);

	}
	
	private void initAnimation() {
		mAnimIn = AnimationUtils.loadAnimation(this, R.anim.anim_register_in);
		mAnimOut = AnimationUtils.loadAnimation(this, R.anim.anim_register_out);
	}
	
	private void initRegisterInputFieldButton() {
		// one line
		Button inputCancelButton = (Button) findViewById(R.id.inputfield_cancelbutton);
		inputCancelButton.setOnClickListener(new OnClickListener() {

			public void onClick(View v) {
				hideOneLineInputField();
			}
		});

		Button inputOkButton = (Button) findViewById(R.id.inputfield_okbutton);
		inputOkButton.setOnClickListener(new OnClickListener() {

			public void onClick(View v) {
				String account = mInputFieldOneLineEditText.getText().toString().trim();
				if(!account.equals("")){
					int status = initGetPassword(account);
					if(status == Constant.RESP_STATUS_SUCCESS){
						Toast.makeText(FirstLoginActivity.this, getString(R.string.send_email_success), Toast.LENGTH_LONG).show();
					}else{
						Toast.makeText(FirstLoginActivity.this, getString(R.string.send_email_fail), Toast.LENGTH_LONG).show();
					}
				}
			}
		});
	}
	
	private void hideOneLineInputField() {
		mInputFieldOneLineEditText.setText("");
		mInputFieldOneLineEditText.setInputType(InputType.TYPE_NULL);
		mInputFieldOneLineEditText.clearFocus();
		mInputFieldOneLine.startAnimation(mAnimOut);
		mInputFieldOneLine.setVisibility(View.GONE);
		imm.toggleSoftInput(InputMethodManager.SHOW_FORCED, 0);
	}
	
	private void showOneLineInputField() {
		mInputFieldOneLine.startAnimation(mAnimIn);
		mInputFieldOneLine.setVisibility(View.VISIBLE);
		mInputFieldOneLineTextView.setText(getString(R.string.forget_pwd_text));
		mInputFieldOneLineEditText.requestFocus();
		imm.toggleSoftInput(InputMethodManager.SHOW_FORCED, 0);
	}
	
	public void forgetView_OnClick(View v){
		showOneLineInputField();
	}
	
	public void registerButton_OnClicked(View v) {
		mAnimCancelled.getAndSet(true);
		Intent intent = new Intent(this, RegisterFirstViewActivity.class);
		startActivity(intent);
	}

	public int initGetPassword(String account){
		JSONObject jsonData = new JSONObject();
		int status = -1;
		JSONResponse jsonResponse = null;
		try {
			jsonData.put("user_account", account);
			
			jsonResponse = JSONUtil.postRequest(Constant.REQ_WAY_FORGETPASSWORD, jsonData);
			if(jsonResponse.getStatus() != Status.ERR){
				JSONObject data = jsonResponse.getData();
				
				status = data.getInt(Constant.RESP_STATUS);
			}
		} catch (Exception e) {
			// TODO: handle exception
			
			e.printStackTrace();
		}
		return status;
	}
	
	public void loginButton_OnClicked(View v) {
		mLoginAnimIn = AnimationUtils.loadAnimation(FirstLoginActivity.this, R.anim.anim_login_in);
		View forgetPwdView = (View)findViewById(R.id.forget_password);
		temp ++;
		if(temp %2 == 1){
			forgetPwdView.setVisibility(View.VISIBLE);
			mLoginView.setVisibility(View.VISIBLE);
			mLoginView.setAnimation(mLoginAnimIn);
			forgetPwdView.setAnimation(mLoginAnimIn);
			usernameEdit = (EditText)mLoginView.findViewById(R.id.username_edittext);
			usernameEdit.requestFocus();
			
			passwordEdit = (EditText)mLoginView.findViewById(R.id.password_edittext);
			Button loginBtn = (Button)mLoginView.findViewById(R.id.loginBtn);
			loginBtn.setOnClickListener(new OnClickListener() {
				
				public void onClick(View v) {
					// TODO Auto-generated method stub
					if (usernameEdit.getText().toString().trim().equals("")) {
						ViewsUtil.showErrorTip(FirstLoginActivity.this, R.string.login_username_errortip);
						return ;
					}
					if (passwordEdit.getText().toString().trim().equals("")) {
						ViewsUtil.showErrorTip(FirstLoginActivity.this, R.string.login_password_errortip);
						return;
					}
					mHandler.sendEmptyMessage(LOGINING_CODE);
				}
			});
		}
		else{
			mLoginAnimOut = AnimationUtils.loadAnimation(FirstLoginActivity.this, R.anim.anim_login_out);
			mLoginView.setAnimation(mLoginAnimOut);
			mLoginView.setVisibility(View.INVISIBLE);
			forgetPwdView.setAnimation(mLoginAnimOut);
			forgetPwdView.setVisibility(View.INVISIBLE);
			
		}
	}

	private int login() {
		String username = usernameEdit.getText().toString().trim();
		String password = passwordEdit.getText().toString().trim();
		JSONObject jsonData = new JSONObject();
		JSONResponse jsonResponse = new JSONResponse();
		int status = -1;
		try {
			jsonData.put(Constant.PARAM_ACCOUNT, username);
			jsonData.put(Constant.PARAM_PASSWORD, password);
			jsonResponse = JSONUtil.postRequest(Constant.REQ_WAY_LOGIN, jsonData);
		} catch (Exception e) {
			jsonResponse.setStatus(Status.ERR);
			e.printStackTrace();
		}
		if (jsonResponse.getStatus() == Status.ERR) {
			ViewsUtil.showErrorTip(FirstLoginActivity.this, R.string.global_error_networkerr);
		} else {
			try {
				JSONObject data = jsonResponse.getData();
				status = data.getInt(Constant.RESP_STATUS);
				if (status == Constant.RESP_STATUS_SUCCESS) {
					mAnimCancelled.getAndSet(true);
					JSONObject jsonObject = data.getJSONObject(Constant.RESP_USERACCOUNT);
					Gson gson = new Gson();
					LoginAccountEntity loginAccount = gson.fromJson(jsonObject.toString(), LoginAccountEntity.class);
					
					UserInfoDAO.setUserInfo(getApplicationContext(), geUuserInfoEntity(loginAccount));
					
					//保存用户信息写在这里
					UserInfoEntity userInfo = new UserInfoEntity();
					userInfo.setUserAccount(username);
					userInfo.setUserPassword(password);
					userInfo.setNickName(loginAccount.getUser_nickname());
					userInfo.setAvatarUrl(loginAccount.getUser_avatar());
					UserInfoDAO.setUserInfo(FirstLoginActivity.this, userInfo);
					
				} else {
					ViewsUtil.showErrorTip(FirstLoginActivity.this, R.string.login_errortip);
				}
			} catch (JSONException e) {
				e.printStackTrace();
			}
		}
		
		return status;
	}

	private UserInfoEntity geUuserInfoEntity(LoginAccountEntity loginAccount) {
		UserInfoEntity userInfo = new UserInfoEntity();
		userInfo.setUserId(loginAccount.getUser_id());
		userInfo.setNickName(loginAccount.getUser_nickname());
		String avatarName = loginAccount.getUser_avatar();
		userInfo.setUserAccount(avatarName);
		return userInfo;
	}

	
	public void lookAroundButton_OnClicked(View v) {
		mAnimCancelled.getAndSet(true);
		Intent intent = new Intent(this, LookAroundActivity.class);
		startActivity(intent);
	}

	private final class DisplayNextView implements AnimationListener {
		private int mPosition;

		private DisplayNextView(int position) {
			mPosition = position;
		}

		public void onAnimationStart(Animation animation) {
			mPosition += 1;
			if (mPosition >= Constant.ANIM_FRAME_COUNT) {
				mPosition = 0;
				mCurrentShowLoop += 1;
				initShowAnimImageAndTextData();
			}

		}

		public void onAnimationEnd(Animation animation) {

			if (mAnimCancelled.get()) {
				mContainer.clearAnimation();
				return;
			}
			if (mPosition % 2 == 0) {
				mContainer.postDelayed(new SwapViews(mPosition), Constant.ANIM_DELAY);
			} else {
				mContainer.post(new SwapViews(mPosition));
			}
		}

		public void onAnimationRepeat(Animation animation) {
		}
	}

	private void initShowAnimImageAndTextData() {
		if (mCurrentShowLoop >= mShowLoopCount) {
			mCurrentShowLoop = 0;
			return;
		}
		ShowMsgEntity msgEntity = mShowMsgList.get(mCurrentShowLoop);
		ShowMeetEntity meetEntity = mShowMeetList.get(mCurrentShowLoop);
		ShowRingEntity ringEntity = mShowRingList.get(mCurrentShowLoop);

		if (msgEntity.getMsg_user_avatar() != null) {
			ImageView imageView = new ImageView(this);
			imageLoader.showImageAsyn(imageView, Constant.URL_USER_MIDDLE+msgEntity.getMsg_user_avatar(), R.drawable.av4);
			Drawable drawable = imageView.getDrawable();
			if(drawable != null){
				Bitmap mbitmap = AvatarUtil.drawableToBitmap(drawable);
				Bitmap tempbitmap = AvatarUtil.zoomBitmap(mbitmap, 60, 60);
				Bitmap bitmap = AvatarUtil.getRoundedCornerBitmap(tempbitmap, 20);
				mAnimImageViewMsg1.setImageDrawable(AvatarUtil.Bitmap2Drawable(bitmap));
			}
			else {
				mAnimImageViewMsg1.setImageDrawable(mAvatarTestPic);
			}
		} else {
			mAnimImageViewMsg1.setImageDrawable(mAvatarTestPic);
		}
		mAnimTextViewMsg1.setText(msgEntity.getMsg_user_nickname()+msgEntity.getMsg_content());
		mAnimNameView1.setText(msgEntity.getMsg_user_nickname());
		
		
		if(meetEntity.getMeet_create_avatar() != null){
			ImageView imageView = new ImageView(this);
			imageLoader.showImageAsyn(imageView, Constant.URL_USER_MIDDLE+meetEntity.getMeet_create_avatar(), R.drawable.av4);
			Drawable drawable = imageView.getDrawable();
			if(drawable != null){
				Bitmap mbitmap = AvatarUtil.drawableToBitmap(drawable);
				Bitmap tempbitmap = AvatarUtil.zoomBitmap(mbitmap, 60, 60);
				Bitmap bitmap = AvatarUtil.getRoundedCornerBitmap(tempbitmap, 20);
				mAnimImageViewMsg2.setImageDrawable(AvatarUtil.Bitmap2Drawable(bitmap));
			}
			else {
				mAnimImageViewMsg2.setImageDrawable(mAvatarTestPic);
			}
		}
		else{
			mAnimImageViewMsg2.setImageDrawable(mAvatarTestPic);
		}
		mAnimTextViewMsg2.setText(meetEntity.getMeet_user_nickname()+"创建了" + meetEntity.getMeet_name() + "的聚会");
		mAnimNameView2.setText(meetEntity.getMeet_user_nickname());
		
		if(ringEntity.getRr_master_avatar() != null){
			ImageView imageView = new ImageView(this);
			imageLoader.showImageAsyn(imageView, Constant.URL_USER_MIDDLE+ringEntity.getRr_master_avatar(), R.drawable.av4);
			Drawable drawable = imageView.getDrawable();
			if(drawable != null){
				Bitmap mbitmap = AvatarUtil.drawableToBitmap(drawable);
				Bitmap tempbitmap = AvatarUtil.zoomBitmap(mbitmap, 60, 60);
				Bitmap bitmap = AvatarUtil.getRoundedCornerBitmap(tempbitmap, 20);
				mAnimImageViewMsg3.setImageDrawable(AvatarUtil.Bitmap2Drawable(bitmap));
			}
			else {
				mAnimImageViewMsg3.setImageDrawable(mAvatarTestPic);
			}
		}
		else{
			mAnimImageViewMsg3.setImageDrawable(mAvatarTestPic);
		}
		mAnimTextViewMsg3.setText(ringEntity.getRing_user_nickname()+"创建了圈子" + ringEntity.getRing_name());
		mAnimNameView3.setText(ringEntity.getRing_user_nickname());
	}

	private final class SwapAnimationData implements Runnable {

		private final static String MSG_DATA = "msgData";
		private final static String MEET_DATA = "meetData";
		private final static String RING_DATA = "ringData";

		public void run() {
			JSONResponse jsonResponse = JSONUtil.postRequest(Constant.REQ_WAY_FIRSTLOGIN_ANIM, new JSONObject());
			if (jsonResponse.getStatus() != Status.ERR) {
				JSONObject data = jsonResponse.getData();
				int status = -1;
				JSONObject showData = null;
				try {
					status = data.getInt(Constant.RESP_STATUS);
					showData = data.getJSONObject(Constant.RESP_FIRSTLOGIN_SHOWDATA);
					if (status == Constant.RESP_STATUS_SUCCESS) {
						JSONArray jsonMsgArray = showData.getJSONArray(MSG_DATA);
						JSONArray jsonMeetArray = showData.getJSONArray(MEET_DATA);
						JSONArray jsonRingArray = showData.getJSONArray(RING_DATA);
						Gson gson = new Gson();
						for (int i = 0; i < jsonMsgArray.length(); i++) {
							ShowMsgEntity msgEntity = gson.fromJson(jsonMsgArray.getJSONObject(i).toString(), ShowMsgEntity.class);
							mShowMsgList.add(msgEntity);
						}
						for (int i = 0; i < jsonMeetArray.length(); i++) {
							ShowMeetEntity meetEntity = gson.fromJson(jsonMeetArray.getJSONObject(i).toString(), ShowMeetEntity.class);
							mShowMeetList.add(meetEntity);
						}
						for (int i = 0; i < jsonRingArray.length(); i++) {
							ShowRingEntity ringEntity = gson.fromJson(jsonRingArray.getJSONObject(i).toString(), ShowRingEntity.class);
							mShowRingList.add(ringEntity);
						}
						mShowLoopCount = Math.min(jsonMsgArray.length(), jsonMeetArray.length());
						mShowLoopCount = Math.min(mShowLoopCount, jsonRingArray.length());
					}
					Bitmap avatar = AvatarUtil.getRoundedCornerBitmap(getResources().getDrawable(R.drawable.glm_avarat_testpic), 20);
					mAvatarTestPic = AvatarUtil.Bitmap2Drawable(avatar);
					initShowAnimImageAndTextData();
					mContainer.postDelayed(new SwapViews(0), Constant.ANIM_DELAY);
				} catch (JSONException e) {
					e.printStackTrace();
				}

			} else {
			}
		}
	}

	private final class SwapViews implements Runnable {
		private final int mPosition;

		public SwapViews(int position) {
			mPosition = position;
		}

		public void run() {

			final float centerX = mContainer.getWidth() / 2.0f;
			final float centerY = mContainer.getHeight() / 2.0f;
			Rotate3DAnimation rotation;
			Interpolator interpolator;

			if (mPosition % 2 == 0) {
				interpolator = new AccelerateInterpolator();
			} else {
				interpolator = new DecelerateInterpolator();
			}

			if (mPosition == Constant.ANIM_CONTAINER1_GONE) {
				mAnimContainer1.setVisibility(View.GONE);
				mAnimContainer2.setVisibility(View.VISIBLE);
				mAnimContainer2.requestFocus();
				mAnimContainer3.setVisibility(View.GONE);
				rotation = new Rotate3DAnimation(-90, 0, centerX, centerY, 0.0f, false);
			} else if (mPosition == Constant.ANIM_CONTAINER2_VISIABLE) {
				rotation = new Rotate3DAnimation(0, 90, centerX, centerY, 0.0f, false);
			} else if (mPosition == Constant.ANIM_CONTAINER2_GONE) {
				mAnimContainer1.setVisibility(View.GONE);
				mAnimContainer2.setVisibility(View.GONE);
				mAnimContainer3.setVisibility(View.VISIBLE);
				mAnimContainer3.requestFocus();
				rotation = new Rotate3DAnimation(-90, 0, centerX, centerY, 0.0f, false);
			} else if (mPosition == Constant.ANIM_CONTAINER3_VISIABLE) {
				rotation = new Rotate3DAnimation(0, 90, centerX, centerY, 0.0f, false);
			} else if (mPosition == Constant.ANIM_CONTAINER3_GONE) {
				mAnimContainer1.setVisibility(View.VISIBLE);
				mAnimContainer1.requestFocus();
				mAnimContainer2.setVisibility(View.GONE);
				mAnimContainer3.setVisibility(View.GONE);
				rotation = new Rotate3DAnimation(-90, 0, centerX, centerY, 0.0f, false);
			} else {
				rotation = new Rotate3DAnimation(0, 90, centerX, centerY, 0.0f, false);
			}
			rotation.setDuration(Constant.ANIM_DURATION);
			rotation.setFillAfter(true);
			rotation.setInterpolator(interpolator);
			rotation.setAnimationListener(mDisplayNextView);

			if (mAnimCancelled.get()) {
				mContainer.clearAnimation();
				return;
			}
			mContainer.startAnimation(rotation);
		}
	}
}
